<template>
  <div class="editor-box" :style="editorStyle">
    <Toolbar
      :editor="editorRef"
      :mode="mode"
      style="border-bottom: 1px solid #ccc"
    />
    <Editor
      v-model="valueHtml"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import {ref, computed, shallowRef, watch, onMounted} from 'vue';
import visual from "@/visual/js/visual";

const props = defineProps({
  node: Object,
  compStyle: Object,
  compData: Object
});
const currNode = ref(props.node);
const mode = ref('default');
const valueHtml = ref('');
const editorRef = shallowRef();

const init = () => {
  const compStyle = props.compStyle || {};
  mode.value = compStyle['mode'] || 'default';

  if (!props.compData?.dataSourceType) {
    loadValue();
  }
};

const editorStyle = computed(() => {
  const compStyle = props.compStyle || {};
  let result = 'overflow-y: hidden;';
  result += visual.parseTplNs('width: {value};', compStyle['width'], 'px');
  result += visual.parseTplNs('height: {value};', compStyle['height'], 'px');
  result += visual.parseTpl('overflow: {value};', compStyle['overflow']);
  return result;
});

const handleCreated = (editor) => {
  editorRef.value = editor;
  editor.setHtml(valueHtml.value || '');
};

const loadValue = async() => {
  const dataList = (await visual.loadData(props.compData, {}, {}, currNode.value)).data || [];
  currNode.value.compData.dataList = JSON.stringify(dataList);
  valueHtml.value = dataList.length > 0 && dataList[0]['内容'] || '';
};

watch(() => props.compStyle, () => {
  init();
}, {deep: true});

watch(() => props.compData?.refresh, () => {
  loadValue();
});

onMounted(() => {
  init();
  loadValue();
});
</script>

<style>
.w-e-toolbar {
  z-index: 503!important;
}
.w-e-menu {
  z-index: 502!important;
}
.w-e-text-container{
  z-index: 501!important;
}
</style>

<style scoped>
.editor-box {
  border: 1px solid #ccc;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}
</style>
